
(function($, win, doc){
	
	/**
	 *  默认值：/seeyon
	 */
	var appBasePath = (function(){
		
		var path = location.pathname;
		
		return path.substring(0, path.indexOf('/', 1));
	})();
	
	var groovyMirror = (function (){

		var aesPwd = 'Xxeicq3gknHJEsZR';
		var editor = null;
		var script = null;

		return {
			init: function(){
				
				setTimeout(function(){
					
					if(null != editor){
						
						$.setCSS(editor.getWrapperElement(), {display: 'block'});
						
						return;
					}
					
					if($.isBlank(script)){
						
						$.setEleValue('#script_content', script = (function(){
							
							var scriptTxt = ['#!/snail/common/utils groovy JOBTASK_' + $.random20L()];
							scriptTxt.push('');
							scriptTxt.push('import com.seeyon.ctp.common.AppContext;');
							scriptTxt.push('import com.seeyon.apps.snail.APPLogger;');
							scriptTxt.push('import com.seeyon.apps.snail.common.MessageHepler;');
							scriptTxt.push('');
							scriptTxt.push('import snail.common.ClassHelper;');
							scriptTxt.push('import snail.common.ServiceException;');
							scriptTxt.push('import snail.common.utils.StringHelper;');
							scriptTxt.push('import snail.common.utils.JSONHelper;');
							scriptTxt.push('import snail.common.utils.DateHelper;');
							scriptTxt.push('import snail.common.utils.IDHelper;');
							scriptTxt.push('import snail.common.web.HTTPHelper;');
							scriptTxt.push('');
							scriptTxt.push('');
							scriptTxt.push('/**');
							scriptTxt.push(' * 工作任务');
							scriptTxt.push(' * ');
							scriptTxt.push(' */');
							scriptTxt.push('static main(args) {');
							scriptTxt.push('    ');
							scriptTxt.push('    ');
							scriptTxt.push('    ');
							scriptTxt.push('    ');
							scriptTxt.push('}');
							scriptTxt.push('');
							scriptTxt.push('');
							scriptTxt.push('');
							scriptTxt.push('/** ******************************* 以下为共公函数 ******************************* */');
							scriptTxt.push('include seeyon.common.groovy;');
							scriptTxt.push('');
							
							return scriptTxt.join('\r\n');
						})());
						
					}else{
						$.setEleValue('#script_content', script);
					}
					
					editor = CodeMirror.fromTextArea($.getElement('#script_content'), {
						mode: 'text/x-groovy',
						theme: "darcula",
						lineNumbers: true,
						lineWrapping: true,
						indentUnit: 4,
						extraKeys: {
							'Ctrl': 'autocomplete'
						},
						hintOptions: {
							completeSingle: false,
							hint: $.codemirror.groovyShowHint,
							word: {
								__WORD_LIST__: [
									'getObjBySQL(sqlStr, closure, nodata_closure=null)', 'getObjBySQL(sqlStr, args, closure, nodata_closure)', 
									'getListBySQL(sqlStr, closure, nodata_closure=null)', 'getListBySQL(sqlStr, args, closure, nodata_closure)',
									'getSQLClient()', 'sendMessage(txt, receiver=null)', 'logger(txt)', 'GLOBALS(key, value=null)', 'NVL(obj, Object... obj2)'
								]
							}
						}
					});
					
					editor.on('keypress', function(){
						//编译器内容更改事件
						editor.showHint();
					});
					
					editor.refresh();
					
				}, 200);
			},
			getCode: function(){
				
				script = editor.getValue();
				
				var code = script.match(/\#\!\/snail\/common\/utils\s+groovy\s+[^\r\n]+/);
				code = ((code && 1 == code.length) ? code[0] : '');
				code = code.replace(/\#\!\/snail\/common\/utils\s+groovy\s+/, '');
				code = code.replace(/\s+/, '');
				
				return code;
			},
			setValue: function(_script){

				script = (_script ? $.aes_decrypt(_script, aesPwd) : generateTemplate());
				
				if(null == editor){
					return ;
				}
				
				editor.setValue(script);
			},
			getValue: function(){
				return $.aes_encrypt((editor ? editor.getValue() : script), aesPwd);
			},
			close: function(){
				editor && $.setCSS(editor.getWrapperElement(), {display: 'none'});
			}
		}
	})();
	
	var app = new Vue({
		el: '#app',
		data: {
			basic:{
				
			},
			style:{
				
			},
			formData:{
				fields:{
					id: null,
					name: '',
					code: '',
					cron: '0 5 * * * ?',
					description: ''
				},
				rules: {
				  name: [
					  { required: true, message: '请输入名称', trigger: 'blur' },
					  { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
				  ],
				  cron: [
					  { required: true, message: '请输入Cron表达式', trigger: 'blur' },
					  { 
						  validator: function(rule, value, callback){
							  
							  /**
							   * 
							   * Cron表达式格式的正则表达式：
							   * 
							   * 	秒：        (\*|([1-5]?[0-9]([\,][1-5]?[0-9])*)|([1-5]?[0-9]\-[1-5]?[0-9])|(([\*]|([1-5]?[0-9]))\/[1-5]?[0-9]))
							   * 	分：        \s(\*|([1-5]?[0-9]([\,][1-5]?[0-9])*)|([1-5]?[0-9]\-[1-5]?[0-9])|(([\*]|([1-5]?[0-9]))\/[1-5]?[0-9]))
							   * 	时：        \s(\*|(([0-9]|(1[0-9])|(2[0-3]))([\,]([0-9]|(1[0-9])|(2[0-3])))*)|(([0-9]|(1[0-9])|(2[0-3]))\-([1-9]|(1[0-9])|(2[0-3])))|(([\*0-9]|(1[0-9])|(2[0-3]))\/([1-9]|(1[0-9])|(2[0-3]))))
							   * 	天（月）：   \s(\*|\?|(([1-9]|([12][0-9])|(3[01]))([\,]([1-9]|([12][0-9])|(3[01])))*)|(([1-9]|([12][0-9])|(3[01]))\-([1-9]|([12][0-9])|(3[01])))|(([\*1-9]|([12][0-9])|(3[01]))\/([1-9]|([12][0-9])|(3[01])))|(([1-9]|([12][0-9])|(3[01]))[LWC])|(LW)|L)
							   * 	月：        \s(\*|(([1-9]|(1[0-2]))([\,]([1-9]|(1[0-2])))*)|(([1-9]|(1[0-2]))\-([1-9]|(1[0-2])))|(([\*1-9]|(1[0-2]))\/([1-9]|(1[0-2])))|L)
							   * 	天（周）：   \s(\*|\?|([1-7]([\,][1-7])*)|([1-7]\-[1-7])|([\*1-7]\/[1-7])|([1-7]?[LC])|([1-7]#[2-5]))
							   * 	年：        (\s(\*|([1-9]\d{3}([\,][1-9]\d{3})*)|([1-9]\d{3}\-[1-9]\d{3})|(([\*]|([1-9]\d{3}))\/[1-9]\d{0,3})))?
							   * 
							   * 	注： 【天（月）】与【天（周）】不能同时设置，有且有一个为【?】
							   */
							  if(/^[^\?]+\?[^\?]*$/.test(value)
									  && /^(\*|([1-5]?[0-9]([\,][1-5]?[0-9])*)|([1-5]?[0-9]\-[1-5]?[0-9])|(([\*]|([1-5]?[0-9]))\/[1-5]?[0-9]))\s(\*|([1-5]?[0-9]([\,][1-5]?[0-9])*)|([1-5]?[0-9]\-[1-5]?[0-9])|(([\*]|([1-5]?[0-9]))\/[1-5]?[0-9]))\s(\*|(([0-9]|(1[0-9])|(2[0-3]))([\,]([0-9]|(1[0-9])|(2[0-3])))*)|(([0-9]|(1[0-9])|(2[0-3]))\-([1-9]|(1[0-9])|(2[0-3])))|(([\*0-9]|(1[0-9])|(2[0-3]))\/([1-9]|(1[0-9])|(2[0-3]))))\s(\*|\?|(([1-9]|([12][0-9])|(3[01]))([\,]([1-9]|([12][0-9])|(3[01])))*)|(([1-9]|([12][0-9])|(3[01]))\-([1-9]|([12][0-9])|(3[01])))|(([\*1-9]|([12][0-9])|(3[01]))\/([1-9]|([12][0-9])|(3[01])))|(([1-9]|([12][0-9])|(3[01]))[LWC])|(LW)|L)\s(\*|(([1-9]|(1[0-2]))([\,]([1-9]|(1[0-2])))*)|(([1-9]|(1[0-2]))\-([1-9]|(1[0-2])))|(([\*1-9]|(1[0-2]))\/([1-9]|(1[0-2])))|L)\s(\*|\?|([1-7]([\,][1-7])*)|([1-7]\-[1-7])|([\*1-7]\/[1-7])|([1-7]?[LC])|([1-7]#[2-5]))(\s(\*|([1-9]\d{3}([\,][1-9]\d{3})*)|([1-9]\d{3}\-[1-9]\d{3})|(([\*]|([1-9]\d{3}))\/[1-9]\d{0,3})))?$/g.test(value)){
								  
								  callback();
								  
							  }else{
								  callback(new Error('暂不支持该 Cron 表达式！'));
							  }
						  }, 
						  trigger: 'blur' 
					  }
				  ]
				}
			}
		},
		methods:{
			init: function(){
				
				groovyMirror.init();
				
				this.loadScriptInfo();
				
			},
			loadScriptInfo: function(){
				
				var code = $.request.getParament('code');
				
				if($.isBlank(code)){
					return ;
				}
				
				var _this = this;
				
				$.http.get({
					url: (appBasePath + '/snail/jobtask.do?method=getGroovyJob'),
					header: {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'},
					data: {code: code},
					onsuccess: function(result, status, xhr){
						
						if(200 == result.code){
							
							_this.setFormData(result.data);
							
						}else{
							_this.$alert(result.message, '信息');
						}

					},
					onerror: function(responseText, status, xhr){
						console.log(responseText);
					}
				});
			},
			getCode: function(){
				
				return this.formData.fields.code = groovyMirror.getCode();
			},
			getFormData: function(){
				
				var data = $.extend({code: null, script: null}, this.formData.fields, true);
				
				data.code = this.formData.fields.code = groovyMirror.getCode();
				data.script = groovyMirror.getValue();
				
				return data;
			},
			setFormData: function(data){
				
				groovyMirror.setValue(data.script);
				
				$.extend(this.formData.fields, data, true);
				
			},
			onTest: function(){
				
				var _this = this;
				var loading = this.$loading({lock: true, text: 'Loading', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.8)'});
				
				this.$refs.formData.validate(function(valid){
					
					if(valid){

						$.http.post({
							url: (appBasePath + '/snail/jobtask.do?method=test'),
							header: {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'},
							data: {code: _this.getCode()},
							onsuccess: function(result, status, xhr){
								
								_this.$alert(result.message, '信息');
							},
							onerror: function(responseText, status, xhr){
								console.log(responseText);
							},
							oncomplete: function(responseText, status, xhr){
								loading.close();
							}
						});
					}else{
						alert('数据校验不通过！');
					}
				});
			},
			onSave: function(){
				
				var _this = this;
				
				this.$refs.formData.validate(function(valid){
					
					if(valid){

						$.http.post({
							url: (appBasePath + '/snail/jobtask.do?method=save'),
							header: {'Content-Type': 'application/json', 'Accept': 'application/json'},
							data: _this.getFormData(),
							onsuccess: function(result, status, xhr){
								
								_this.$alert(result.message, '信息');

							},
							onerror: function(responseText, status, xhr){
								console.log(responseText);
							}
						});
					}else{
						alert('数据校验不通过！');
					}
				});
			},
			/**
			 * 注入到计划任务中 （Quartz）
			 */
			onInject: function(){
				
				var _this = this;
				
				this.$refs.formData.validate(function(valid){
					
					if(valid){

						$.http.post({
							url: (appBasePath + '/snail/jobtask.do?method=inject'),
							header: {'Content-Type': 'application/json', 'Accept': 'application/json'},
							data: _this.getFormData(),
							onsuccess: function(result, status, xhr){
								
								_this.$alert(result.message, '信息');

							},
							onerror: function(responseText, status, xhr){
								console.log(responseText);
							}
						});
					}else{
						alert('数据校验不通过！');
					}
				});
			}
		},
		created: function(){
			this.init();
		}
	});
	
	
})(Snail, window, document);